#!/usr/bin/env python
import sys
import helper
import class_set
from sets import Set

class SumReducer(helper.ReducerHelper):

    def decision(self, recom_atom, reason):
        retval = True
        if reason == 'follow' or reason == 'friend':
            if len(recom_atom.involved_ids) < 3:
                retval = False
        elif reason == 'resource' or reason == 'like' or reason == 'comment':
            if len(recom_atom.involved_ids) < 10:
                retval = False
        else:
            pass
        return retval

    def trasferReason(self, reason):
        if reason == 'follow':
            return '002'
        elif reason == 'friend':
            return '001'
        elif reason == 'resource':
            return '003'
        elif reason == 'comment':
            return '004'
        elif reason == 'like':
            return '005'
        else:
            return None


    def processor(self, key, lst):
        uid, reason = self.split(key)
        recom_result = class_set.RecomResult()
        recom_result.ppuid = uid
        recom_result.reason_id = self.trasferReason(reason)
        recom_result.reason_desc = reason
        res = {}
        record = {}
        for e in lst:
            left, right = self.split(e)
            if left not in res:
                res[left] = []
            recom_tag = class_set.RecomTag('')
            recom_tag.init(right)
            res[left].append(recom_tag)

        for e in res.keys():
            recom_atom = class_set.RecomAtom()
            for l in res[e]:
                recom_atom.involved_ids.append(l.getRelatedId())
            recom_atom.item_id = e
            recom_atom.involved_num = len(recom_atom.involved_ids)
            if self.decision(recom_atom, reason):
                record[e] = recom_atom
            else:
                pass
        
        for e in record:
            recom_result.resys_items.append(record[e])

        if (recom_result.reason_id == '001' or recom_result.reason_id == '002' or recom_result.reason_id == '003'):
            if len(recom_result.resys_items) != 0:
                print recom_result       
        else:
                print recom_result


def main():
    sr = SumReducer()
    sr.reducer()


if __name__ == '__main__':
    main()

